/*
 * @lc app=leetcode.cn id=671 lang=typescript
 *
 * [671] 二叉树中第二小的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findSecondMinimumValue(root: TreeNode | null): number {
  let ans = -1;
  // 根节点的值是最小的值
  const rootVal: number = root.val;
  const dfs = (node: TreeNode | null) => {
    if (node === null) return;
    if (ans !== -1 && node.val >= ans) return;
    // 寻找严格大于根节点的值
    if (node.val > rootVal) ans = node.val;
    dfs(node.left);
    dfs(node.right);
  };

  dfs(root);
  return ans;
}
// @lc code=end
